#include "painterwidget.h"
#include "mainwindow.h"

#include <QApplication>
#include <QMimeData>
#include <QImage>
#include <QDebug>

PainterWidget::PainterWidget(QWidget *parent) : QWidget(parent)
{
    _lpress = false;//初始鼠标左键未按下
    _begin = pos();//拖拽的参考坐标，方便计算位移
    _openflag = 0;//初始不打开图片
    setMouseTracking(true);//开启鼠标实时追踪，监听鼠标移动事件，默认只有按下时才监听
    //设置背景颜色
    this->setStyleSheet("background-color:white;");
    this->setAcceptDrops(true);
    m_proc_cnt = 0;
    m_check_btn = new QPushButton("Check", this);
    m_check_btn->setGeometry(180, 480, 80, 20);
    connect(m_check_btn, &QPushButton::clicked, this, [ = ] {
        MainWindow * mainWindow = nullptr;
        foreach (QWidget *w, qApp->topLevelWidgets())
            if (MainWindow *mainWin = qobject_cast<MainWindow * >(w))
                mainWindow = mainWin;
        if (mainWindow) {
            QString res = mainWindow->execRecognition(SavePic());
            mainWindow->addItem(res);
        }
        // 清空画布
        _lines.clear();
        _shape.clear();
        update();
    });
}

void PainterWidget::paintEvent(QPaintEvent *)
{
    if(_openflag == 0) { //不是打开图片的，每一次新建一个空白的画布
        _pixmap = QPixmap(size());//新建pixmap
        _pixmap.fill(Qt::white);//背景色填充为白色
    }
    QPixmap pix = _pixmap;//以_pixmap作为画布
    QPainter p(&pix);//将_pixmap作为画布
    p.setRenderHint(QPainter::Antialiasing);
    p.setPen(QPen(Qt::black, 5));
    unsigned int i1 = 0; //线条索引
    for(int c = 0; c < _shape.size(); ++c) { //控制用户当前所绘图形总数
        if(_shape.at(c) == 1) { //线条
            const QVector<QPoint>& line = _lines.at(i1++);//取出一条线条
            for(int j = 0; j < line.size() - 1; ++j) { //将线条的所有线段描绘出
                p.drawLine(line.at(j), line.at(j + 1));
            }
        }
    }
    p.end();
    p.begin(this);//将当前窗体作为画布
    p.drawPixmap(0, 0, pix); //将pixmap画到窗体
}

void PainterWidget::mousePressEvent(QMouseEvent *e)
{
    setFocus();
    if(e->button() == Qt::LeftButton) { //当鼠标左键按下
        _lpress = true;//左键按下标志
        QVector<QPoint> line;//鼠标按下，新的线条开始
        _lines.append(line);//将新线条添加到线条集合
        QVector<QPoint>& lastLine = _lines.last();//拿到新线条
        lastLine.append(e->pos());//记录鼠标的坐标(新线条的开始坐标)
        _shape.append(1);
    }
}

void PainterWidget::mouseReleaseEvent(QMouseEvent *e)
{
    if(_lpress) {
        QVector<QPoint>& lastLine = _lines.last();//最后添加的线条，就是最新画的
        lastLine.append(e->pos());//记录线条的结束坐标
        _lpress = false;//标志左键释放
    }
}

void PainterWidget::mouseMoveEvent(QMouseEvent *e)
{
    if(_lpress) {
        if(_lines.size() <= 0) {
            return;    //线条集合为空，不画线
        }
        QVector<QPoint>& lastLine = _lines.last();//最后添加的线条，就是最新画的
        lastLine.append(e->pos());//记录鼠标的坐标(线条的轨迹)
        update();//触发窗体重绘
    }
}

void PainterWidget::keyPressEvent(QKeyEvent *e)
{
    //Ctrl+Z撤销
    if (e->key() == Qt::Key_Z && e->modifiers() == Qt::ControlModifier) {
        if(_shape.size() > 0) {
            _lines.pop_back();
            _shape.pop_back();
            update();
        }
    }
//    else if (e->key() == Qt::Key_S && e->modifiers() == Qt::ControlModifier) { //保存
//        SavePic();//Ctrl+S保存
//    }
}

void PainterWidget::dragEnterEvent(QDragEnterEvent *event)
{
    if(event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

void PainterWidget::dropEvent(QDropEvent *event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    if(urls.empty()) {
        return;
    }
    QString fileName = urls.first().toLocalFile();
    if(fileName.isEmpty()) {
        return;
    }
    if(OpenPic(fileName)) {
        setWindowTitle(QString("%1-Image").arg(fileName));
    }
}

QString PainterWidget::SavePic()
{
    QString fileName = QDir::currentPath() + tr("/cache/%1.jpg").arg(m_proc_cnt);
    if (fileName.length() > 0) {
        QPixmap pixmap(size());//新建窗体大小的pixmap
        QPainter painter(&pixmap);//将pixmap作为画布
        painter.fillRect(QRect(0, 0, size().width(), size().height()), Qt::white);//设置绘画区域、画布颜色
        this->render(&painter);//将窗体渲染到painter，再由painter画到画布
        //不包含按钮
        if (!pixmap.copy(QRect(0, 30, size().width(), size().height() - 60)).save(fileName)) {
            qDebug() << "[ERROR] Save Picture Failed";
        } else {
            m_proc_cnt++;
        }
    }
    return fileName;
}

bool PainterWidget::OpenPic(const QString &path)
{
    QString picPath;
    if (path == "")
        //弹出文件打开对话框
    {
        picPath = QFileDialog::getOpenFileName(this, tr("打开"), "", "Image Files(*.jpg *.png)");
    }
    picPath = path;
    if(!picPath.isEmpty()) { //用户选择了文件
        QPixmap pix;
        //加载图片
        if (!pix.load(picPath)) {
            return false;
        }
        QPainter p(&_pixmap);
        p.drawPixmap(0, 30, pix); //添加工具栏的空间
        _openflag = 1;//设置文件打开标志
        update();//触发窗体重绘，将图片画到窗体
    } else {
        return false;
    }
    return true;
}
